package com.richbond.sdjdsm.common;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.richbond.sdjdsm.R;
import com.richbond.sdjdsm.entity.CityModel;
import com.richbond.sdjdsm.entity.DistrictModel;
import com.richbond.sdjdsm.entity.ProvinceModel;
import com.richbond.sdjdsm.util.RegionHandler;
import com.richbond.sdjdsm.util.SystemUtil;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * Created by liwenxun on 15/8/12.
 *
 * @author Administrator
 *         碎片的基类，定义了标题栏，给子类提供正在加载等方法
 */
public class BaseFragment extends Fragment {

    private static final String TAG = BaseFragment.class.getSimpleName();
    protected IFragmentRefreshInterface refreshInterface;
    protected IFragmentOnItemClickInterface itemClickInterface;
    private FrameLayout base_content;
    private LinearLayout base_viewloading, base_view_load_fail,
            base_view_load_nodata;
    protected View view;

    private ImageView base_ivloadingfail;
    private TextView base_txt_neterr;

    public void setRefreshInterface(IFragmentRefreshInterface refresh) {
        this.refreshInterface = refresh;
    }

    public void setItemClickInterface(
            IFragmentOnItemClickInterface onItemClickInterface) {
        this.itemClickInterface = onItemClickInterface;
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        // TODO Auto-generated method stub
        super.onSaveInstanceState(outState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // container.removeAllViews();
        // return inflater.inflate(R.layout.base_fragment_layout, null);
        return view;
    }

    @Override
    public void onDestroyView() {
        try {
            ViewGroup viewp = (ViewGroup) view.getParent();
            viewp.removeView(view);
        } catch (Exception e) {
            // TODO: handle exception
        }
        super.onDestroyView();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LayoutInflater inflater = getLayoutInflater(savedInstanceState);
        view = inflater.inflate(R.layout.base_fragment_layout, null);
        base_content = (FrameLayout) view.findViewById(R.id.base_content);
        base_view_load_fail = (LinearLayout) view
                .findViewById(R.id.base_view_load_fail);
        base_viewloading = (LinearLayout) view
                .findViewById(R.id.base_viewloading);
        base_view_load_nodata = (LinearLayout) view
                .findViewById(R.id.base_view_load_nodata);

        base_ivloadingfail = (ImageView) base_view_load_nodata
                .findViewById(R.id.base_ivloadingfail);
        base_txt_neterr = (TextView) base_view_load_nodata
                .findViewById(R.id.base_txt_neterr);
    }

    public void setLoading() {
        try {
            base_viewloading.setVisibility(View.VISIBLE);
            base_view_load_fail.setVisibility(View.GONE);
            base_content.setVisibility(View.GONE);
            base_view_load_nodata.setVisibility(View.GONE);
        } catch (Exception e) {
        }
    }

    public void setEndLoading() {
        try {
            base_viewloading.setVisibility(View.GONE);
            base_view_load_fail.setVisibility(View.GONE);
            base_content.setVisibility(View.VISIBLE);
            base_view_load_nodata.setVisibility(View.GONE);
        } catch (Exception e) {
        }
    }

    public void setLoadingNOdata(int res, String text, View.OnClickListener l) {
        try {
            base_viewloading.setVisibility(View.GONE);
            base_view_load_fail.setVisibility(View.GONE);
            base_view_load_nodata.setVisibility(View.VISIBLE);
            base_content.setVisibility(View.GONE);
            base_ivloadingfail.setImageResource(res);
            if (!TextUtils.isEmpty(text)) {
                base_txt_neterr.setText(text);
                base_txt_neterr.setVisibility(View.VISIBLE);
            }
            if (l != null) {
                base_view_load_nodata.setOnClickListener(l);
            }
        } catch (Exception e) {
        }
    }

    public void setLoadingNOdata(int res, String text, View.OnClickListener l,
                                 boolean isBtn) {
        try {
            base_viewloading.setVisibility(View.GONE);
            base_view_load_fail.setVisibility(View.GONE);
            base_view_load_nodata.setVisibility(View.VISIBLE);
            base_content.setVisibility(View.GONE);
            base_ivloadingfail.setImageResource(res);
            if (!TextUtils.isEmpty(text)) {
                base_txt_neterr.setText(text);
                base_txt_neterr.setVisibility(View.VISIBLE);
            }
        } catch (Exception e) {
        }
    }

    public void setLoadingNOdata(int res, String text, View.OnClickListener l,
                                 String btnText) {
        try {
            base_viewloading.setVisibility(View.GONE);
            base_view_load_fail.setVisibility(View.GONE);
            base_view_load_nodata.setVisibility(View.VISIBLE);
            base_content.setVisibility(View.GONE);
            base_ivloadingfail.setImageResource(res);
            if (!TextUtils.isEmpty(text)) {
                base_txt_neterr.setText(text);
                base_txt_neterr.setVisibility(View.VISIBLE);
            }
        } catch (Exception e) {
        }
    }

    public void setLoadingNOdata() {
        try {
            base_viewloading.setVisibility(View.GONE);
            base_view_load_fail.setVisibility(View.GONE);
            base_view_load_nodata.setVisibility(View.VISIBLE);
            base_content.setVisibility(View.GONE);
        } catch (Exception e) {
        }
    }

    public void setWhiteBG() {
        base_content.setBackgroundColor(Color.WHITE);

    }

    public void setLoadFail() {
        try {
            base_viewloading.setVisibility(View.GONE);
            base_view_load_fail.setVisibility(View.VISIBLE);
            base_content.setVisibility(View.GONE);
            base_view_load_nodata.setVisibility(View.GONE);
        } catch (Exception e) {
        }
    }

    public View setBaseContentLayout(int layoutResId) {
        base_content.removeAllViews();
        LayoutInflater inflater = (LayoutInflater) getActivity()
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View v = inflater.inflate(layoutResId, null);
        base_content.addView(v);
        return view;
    }

    protected void setBlackBG() {
        base_content.setBackgroundColor(Color.BLACK);
    }

    public View setBaseContentView(View v) {
        base_content.removeAllViews();
        base_content.addView(v);
        return view;
    }

    public interface IFragmentRefreshInterface {
        abstract void load(int pageIndex);
    }

    public interface IFragmentOnItemClickInterface {
        abstract void onItemClick(AdapterView<?> parent, View view,
                                  int position, long id, Object object);
    }

    /**
     * 打开新的Activity
     *
     * @param classzz
     * @param bundle
     */
    public void openActivity(Class classzz, Bundle bundle) {
        Intent intent = new Intent();
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        intent.setClass(getActivity(), classzz);
        startActivity(intent);
        getActivity().overridePendingTransition(R.anim.base_push_left_in,
                R.anim.base_push_left_out);
    }

    public void openActivity(Class classzz) {
        openActivity(classzz, null);
    }

    /**
     * 显示输入框错误提示信息
     *
     * @param errorTipStr
     * @param editText
     */
    public void setErrorTip(String errorTipStr, EditText editText) {
        editText.setError(errorTipStr);
        editText.requestFocus();
    }

    /**
     * 所有省
     */
    protected String[] mProvinceDatas;
    /**
     * key - 省 value - 市
     */
    protected Map<String, String[]> mCitisDatasMap = new HashMap<String, String[]>();
    /**
     * key - 市 values - 区
     */
    protected Map<String, String[]> mDistrictDatasMap = new HashMap<String, String[]>();

    /**
     * key - 区 values - 邮编
     */
    protected Map<String, String> mZipcodeDatasMap = new HashMap<String, String>();

    /**
     * 当前省的名称
     */
    protected String mCurrentProviceName;
    /**
     * 当前市的名称
     */
    protected String mCurrentCityName;
    /**
     * 当前区的名称
     */
    protected String mCurrentDistrictName = "";

    /**
     * 当前区的邮政编码
     */
    protected String mCurrentZipCode = "";

    /**
     * 解析省市区的XML数据
     */

    /*protected void initProvinceDatas() {
        List<ProvinceModel> provinceList = null;
        AssetManager asset = getActivity().getAssets();
        InputStream input = null;
        try {
            input = asset.open("province_data.xml");
            // 创建一个解析xml的工厂对象
            SAXParserFactory spf = SAXParserFactory.newInstance();
            // 解析xml
            SAXParser parser = spf.newSAXParser();
            XmlParserHandler handler = new XmlParserHandler();
            parser.parse(input, handler);
            input.close();
            // 获取解析出来的数据
            provinceList = handler.getDataList();
            // 初始化默认选中的省、市、区
            if (provinceList != null && !provinceList.isEmpty()) {
                mCurrentProviceName = provinceList.get(0).getName();
                List<CityModel> cityList = provinceList.get(0).getCityList();
                if (cityList != null && !cityList.isEmpty()) {
                    mCurrentCityName = cityList.get(0).getName();
                    List<DistrictModel> districtList = cityList.get(0).getDistrictList();


                    mCurrentDistrictName = districtList.get(0).getName();
                    mCurrentZipCode = districtList.get(0).getZipcode();
                }
            }
            mProvinceDatas = new String[provinceList.size()];
            for (int i = 0; i < provinceList.size(); i++) {
                // 遍历所有省的数据
                mProvinceDatas[i] = provinceList.get(i).getName();
                List<CityModel> cityList = provinceList.get(i).getCityList();
                String[] cityNames = new String[cityList.size()];
                for (int j = 0; j < cityList.size(); j++) {
                    // 遍历省下面的所有市的数据
                    cityNames[j] = cityList.get(j).getName();
                    List<DistrictModel> districtList = cityList.get(j).getDistrictList();
                    String[] distrinctNameArray = new String[districtList.size()];
                    DistrictModel[] distrinctArray = new DistrictModel[districtList.size()];
                    for (int k = 0; k < districtList.size(); k++) {
                        // 遍历市下面所有区/县的数据
                        DistrictModel districtModel = new DistrictModel(districtList.get(k).getName(), districtList.get(k).getZipcode());
                        // 区/县对应的邮编，保存到mZipcodeDatasMap
                        mZipcodeDatasMap.put(districtList.get(k).getName(), districtList.get(k).getZipcode());
                        distrinctArray[k] = districtModel;
                        distrinctNameArray[k] = districtModel.getName();
                    }
                    // 市-区/县的数据，保存到mDistrictDatasMap
                    mDistrictDatasMap.put(cityNames[j], distrinctNameArray);
                }
                // 省-市的数据，保存到mCitisDatasMap
                mCitisDatasMap.put(provinceList.get(i).getName(), cityNames);
            }
        } catch (Throwable e) {
            e.printStackTrace();
        } finally {
            if (null != input) {
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != asset) {
                asset.close();
            }
        }
    }*/
    protected void initProvinceDatas() {
        List<ProvinceModel> provinceList = null;
        InputStream input = null;
        try {
            String content = SystemUtil.getFromAssets(getActivity(),"region.txt");
            Log.v(TAG,"region.txt文件的数据："+content);
            RegionHandler handler = new RegionHandler();
            handler.initData(content);
            // 获取解析出来的数据
            provinceList = handler.getDataList();
            Log.v(TAG,"provinceList大小："+provinceList.size());
            // 初始化默认选中的省、市、区
            if (provinceList != null && !provinceList.isEmpty()) {
                mCurrentProviceName = provinceList.get(0).getName();
                List<CityModel> cityList = provinceList.get(0).getCityList();
                if (cityList != null && !cityList.isEmpty()) {
                    mCurrentCityName = cityList.get(0).getName();
                    List<DistrictModel> districtList = cityList.get(0).getDistrictList();


                    mCurrentDistrictName = districtList.get(0).getName();
                    mCurrentZipCode = districtList.get(0).getZipcode();
                }
            }
            mProvinceDatas = new String[provinceList.size()];
            for (int i = 0; i < provinceList.size(); i++) {
                // 遍历所有省的数据
                mProvinceDatas[i] = provinceList.get(i).getName();
                List<CityModel> cityList = provinceList.get(i).getCityList();
                String[] cityNames = new String[cityList.size()];
                for (int j = 0; j < cityList.size(); j++) {
                    // 遍历省下面的所有市的数据
                    cityNames[j] = cityList.get(j).getName();
                    List<DistrictModel> districtList = cityList.get(j).getDistrictList();
                    String[] distrinctNameArray = new String[districtList.size()];
                    DistrictModel[] distrinctArray = new DistrictModel[districtList.size()];
                    for (int k = 0; k < districtList.size(); k++) {
                        // 遍历市下面所有区/县的数据
                        DistrictModel districtModel = new DistrictModel(districtList.get(k).getName(), districtList.get(k).getZipcode());
                        // 区/县对应的邮编，保存到mZipcodeDatasMap
                        //mZipcodeDatasMap.put(districtList.get(k).getName(), districtList.get(k).getZipcode());
                        distrinctArray[k] = districtModel;
                        distrinctNameArray[k] = districtModel.getName();
                    }
                    // 市-区/县的数据，保存到mDistrictDatasMap
                    mDistrictDatasMap.put(cityNames[j], distrinctNameArray);
                }
                // 省-市的数据，保存到mCitisDatasMap
                mCitisDatasMap.put(provinceList.get(i).getName(), cityNames);
            }
        } catch (Throwable e) {
            e.printStackTrace();
        } finally {
        }
    }
}
